package com.lin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.Page;
import com.lin.common.context.BaseContext;
import com.lin.common.result.PageResult;
import com.lin.entity.MusicCategory;
import com.lin.entity.Search;
import com.lin.entity.dto.MusicDTO;
import com.lin.entity.vo.MusicVO;
import com.lin.mapper.MusicMapper;
import com.lin.service.MusicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class MusicServiceImpl implements MusicService {


    @Autowired
    private MusicMapper musicMapper;
    /**
     * 获取谱架分类
     * @return
     */
    public List<MusicCategory> getCategory() {
        return musicMapper.getCategory();
    }

    /**
     * 获取每日推荐
     *
     * @return
     */
    public List<MusicVO> getRecommend() {
        return musicMapper.getRecommend();
    }

    /**
     * 按条件分页查询
     *
     * @param musicDTO
     * @return
     */
    @Transactional
    public PageResult getMusic(MusicDTO musicDTO) {
        if(musicDTO.getText() != null && !Objects.equals(musicDTO.getText(), "")){
            Search search  = Search.builder()
                    .text(musicDTO.getText())
                    .time(LocalDateTime.now())
                    .userId(BaseContext.getCurrentId())
                    .build();
            musicMapper.setSearch(search);
        }
        PageHelper.startPage(musicDTO.getPage(),musicDTO.getPageSize());
        Page<MusicVO> page = musicMapper.getMusic(musicDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 获取用户的搜索历史
     * @param userId
     * @return
     */
    public List<Search> getSearchByUserId(Integer userId) {
        return musicMapper.getSearchByUserId(userId);
    }

    /**
     * 获取热门搜索
     * @return
     */
    public List<String> getPopularSearches() {
        return musicMapper.getPopularSearches();
    }

    /**
     * 删除用户搜索记录
     * @param search
     */
    public void deleteSearch(Search search) {
        musicMapper.deleteSearch(search);
    }

    /**
     * 获取乐谱详情
     * @param id
     * @return
     */
    public MusicVO getMusicDetail(Integer id) {
        return musicMapper.getMusicDetail(id);
    }


    /**
     * 更新乐谱数据
     * @param musicVO
     */
    public void updateMusic(MusicVO musicVO) {
        musicMapper.updateMusic(musicVO);
    }

}
